<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>

<html>
<head>

<%@ include file="/WEB-INF/views/include/common.jsp"%>
<title>Test</title>
<style>
.highlighter{
background-color:#FFFFCC
}
</style>
<script type="text/javascript">
	/**
	 * 
	 메모
	 예쁘게 객체로 만드는 중이다.
	 상태, 데이타, 로직
	 세 개의 객체가 있을 예정이다.
	 상태에는 현재 border가 있다.
	 데이타에는 line, marker, table 세 개가 들어간다.
	 로직에는 현재 border로 라인을 전체 그린다.
	 zoom에 따라 marker를 그린다.
	 테이블에는 시간별로 들어간다.
	
	 border를 벗어나는 라인이 있으면 새롭게 라인을 생성한다.
	
	 화면이 이동하면 border를 벗어난 라인만 새로 그리고, 마커의 사이의 거리를 확인해서
	 마커를 새로 그린다.
	
	
	
	
	
	
	 */

	var MapData = function() {
	};

	var MapStatus = function() {
		/**
		현재 border
		 */
		this.nowBorder = this.newBorder();
		/**
		 * 직전 border
		 */
		this.preBorder = this.newBorder();
		/**
		통합 border
		 */
		this.border = this.newBorder();
	};

	/*
	 *
	 ┌──────┐nelat 북위 38.27
	 │　　　　　　│nelng 동경 131.52
	 │　　　　　　│
	 │　　　　　　│
	 │　　　　　　│
	 └──────┘
	 swlat 북위 33.06	
	 swlng 동경 125.04
	 *
	 *swLat, swLng, neLat, neLng
	 */

	MapStatus.prototype.newBorder = function(swLat, swLng, neLat, neLng) {
		return new function() {
			if (isNaN(swLat)) { // 숫자가 아니면 null로 처리한다.
				swLat = null;
			}
			if (isNaN(swLng)) { // 숫자가 아니면 null로 처리한다.
				swLng = null;
			}
			if (isNaN(neLat)) { // 숫자가 아니면 null로 처리한다.
				neLat = null;
			}
			if (isNaN(neLng)) { // 숫자가 아니면 null로 처리한다.
				neLng = null;
			}

			this.swLat = swLat || Number.MAX_VALUE; // 위도 남->북 커진다.  
			this.swLng = swLng || Number.MAX_VALUE; // 경도 서->동 커진다.
			this.neLat = neLat || Number.MIN_VALUE; // 위도 남->북 커진다.
			this.neLng = neLng || Number.MIN_VALUE; // 경도 서->동 커진다.	
		};

	};

	MapStatus.prototype.reset = function() {
		/**
		현재 border
		 */
		delete this.nowBorder;
		this.nowBorder = this.newBorder();

		/**
		 * 직전 border
		 */
		delete this.preBorder;
		this.preBorder = this.newBorder();

		/**
		통합 border
		 */
		delete this.border;
		this.border = this.newBorder();
	};

	/**
	 * 현재 border 가지고 오기.
	 */
	MapStatus.prototype.getNowBorder = function() {
		return this.nowBorder;
	};

	/**
	 * 현재 border 를 저장한다.
	 * 두가지 방법으로 param을 넘긴다.
	 1)border
	 2)swlat, swlng, nelat, nelng
	 둘 중 하나만 허용한다.
	 preBorder에 현재 border를 set한다.
	 현재 border를 리턴한다.
	 @param1 border 객체
	 @param2 swlat, swlng, nelat, nelng
	 @return nowBorder
	 */
	MapStatus.prototype.setNowBorder = function(arg1, arg2, arg3, arg4) {
		logs('setNowBorder');

		if (isNaN(arg1) && typeof arg1 == 'object') {
			logs(arg1);
			var tmp = this.nowBorder;
			this.nowBorder = arg1;
			this.setPreBorder(tmp); // 이전 값을 현재 값으로 세팅한다.
		} else {
			logs('arg1 = ' + arg1 + 'arg2 = ' + arg2 + 'arg3 = ' + arg3
					+ 'arg4 = ' + arg4);
			if (isNaN(arg1) || isNaN(arg2) || isNaN(arg3) || isNaN(arg4)) { // 하나라도 숫자가 아니면 에러이다.
				logs('setNowBorder error');
				return;
			} else {
				var tmp = this.nowBorder;
				var border = this.newBorder(arg1, arg2, arg3, arg4);
				this.nowBorder = border;
				this.setPreBorder(tmp); // 이전 값을 현재 값으로 세팅한다.
			}
		}
		return this.getNowBorder();
	};

	/**
	 * 직전 border 가지고 오기.
	 */
	MapStatus.prototype.getPreBorder = function() {
		return this.preBorder;
	};

	/**
	 * 직전 border 를 저장한다.
	 * 두가지 방법으로 param을 넘긴다.
	 1)border
	 2)swlat, swlng, nelat, nelng
	 둘 중 하나만 허용한다.
	 preBorder 저장한 뒤 border를 만든다.
	 pre border를 리턴한다.
	 @param1 border 객체
	 @param2 swlat, swlng, nelat, nelng
	 @return preBorder
	 */
	MapStatus.prototype.setPreBorder = function(arg1, arg2, arg3, arg4) {
		logs('setPreBorder');
		try {
			if (isNaN(arg1) && typeof arg1 == 'object') {
				logs(arg1);
				this.preBorder = arg1;
			} else {
				logs('arg1 = ' + arg1 + 'arg2 = ' + arg2 + 'arg3 = ' + arg3
						+ 'arg4 = ' + arg4);
				if (isNaN(arg1) || isNaN(arg2) || isNaN(arg3) || isNaN(arg4)) { // 하나라도 숫자가 아니면 에러이다.
					logs('setPreBorder error');
					return;
				} else {
					var border = this.newBorder(arg1, arg2, arg3, arg4);
					this.preBorder = border;
				}
			}
		} catch (e) {
			logs('catch : setPreBorder error');
			logs('arg1 = ' + arg1 + 'arg2 = ' + arg2 + 'arg3 = ' + arg3
					+ 'arg4 = ' + arg4);
			logs(e);
		} finally {
			this.makeBorder(); // border 를 세팅한다. 현재+직전+border 세 개의 값을 종합해서 결정한다.	
		}

		return this.getPreBorder();
	};

	/**
	 * 통합 border 가지고 오기.
	 */
	MapStatus.prototype.makeBorder = function() {

		var nowBorder = this.getNowBorder();
		if (nowBorder.swLat == Number.MAX_VALUE)
			return null; //초기화 된적이 없으면 
		logs(1);
		var border = this.border;
		logs('border.swLat = ' + border.swLat + ', nowBorder.swLat= '
				+ nowBorder.swLat);
		logs(border.swLat > nowBorder.swLat ? 'a' : 'b');
		this.border.swLat = Math.min(border.swLat, nowBorder.swLat);
		this.border.swLng = Math.min(border.swLng, nowBorder.swLng);

		this.border.neLat = Math.max(border.neLat, nowBorder.neLat);
		this.border.neLng = Math.max(border.neLng, nowBorder.neLng);

		return this.border;
	};

	/**
	 * border 세팅하기.
	 참조 setNowBorder
	 */
	MapStatus.prototype.setBorder = function(arg1, arg2, arg3, arg4) {
		return this.setNowBorder(arg1, arg2, arg3, arg4);
	};

	/**
	 * 통합 border 가지고 오기.
	 */
	MapStatus.prototype.getBorder = function() {

		return this.border;
	};

	var MapUtil = function() {
		this.MapStatus = _daumMap && _daumMap.MapStatus;
		if (!this.MapStatus) {
			this.MapStatus = new MapStatus();
		}
	};

	/** return MapStatus.newBorder */
	MapUtil.prototype.getMapBorder = function() {
		if (typeof getBounds == 'function') {
			try {
				var latLngBounds = getBounds();
				var swLatLng = latLngBounds.getSouthWest();
				var neLatLng = latLngBounds.getNorthEast();
				return this.MapStatus.newBorder(swLatLng.getLat(), swLatLng
						.getLng(), neLatLng.getLat(), neLatLng.getLng());
			} catch (e) {
				logs('getMapBorder error');
				logs(e);
			}
		} else {
			logs('------------------');
			logs(typeof getBounds);
		}
		return null;
	};

	MapUtil.prototype.calcMeetBorder = function(srcLatLng, destLatLng) {
		/**
		x  축과 만날 때. y 값을 모름.
		y = (x-x1)*(y2-y1)/(x2-x1)+y1;
		
		y축과 만날 때. x 값을 모름
		x = (y-y1)*(x2-x1)/(y2-y1)+x1;
		
		x1 : src lng,
		y1 : src lat,
		x2 : dest lng,
		y2 : dest lat,
		x : 만나는 border lng,
		y : 만나는 border lat
		 */
	};

	var _daumMap = _this = this;

	_daumMap.MapStatus = new MapStatus();
	_daumMap.MapUtil = new MapUtil();

	$(document).ready(function() {

		logs(_daumMap.MapStatus.getNowBorder());
		logs(_daumMap.MapStatus.getPreBorder());
		logs(_daumMap.MapStatus.getBorder());
		mapInit();
		mapTestArr.push(new daum.maps.LatLng(37.50662, 126.968093));
		var lat = 37.506620, lng = 126.968093;
		for ( var j = 0; j < 37; j++) {
			for ( var i = 0; i < 100; i++) {
				mapTestArr.push(new daum.maps.LatLng(lat, lng));
				lng += 0.001;
			}
			for ( var i = 0; i < 100; i++) {
				mapTestArr.push(new daum.maps.LatLng(lat, lng));
				lat += 0.001;
			}
			for ( var i = 0; i < 100; i++) {
				mapTestArr.push(new daum.maps.LatLng(lat, lng));
				if (j % 2) {
					lng += 0.001;
				} else {
					lng -= 0.001;
				}
			}
			for ( var i = 0; i < 100; i++) {
				mapTestArr.push(new daum.maps.LatLng(lat, lng));
				lat -= 0.001;
			}
		}

		_this.pagingTbl = tableSync('pagingTbl');
		setTestMode(0);
	});

	var border1 = _daumMap.MapStatus.newBorder(36.966354166869124,
			125.98342749285663, 38.071702051552855, 127.79610193623081);
	var border2 = _daumMap.MapStatus.newBorder(36.51161350248626,
			126.92248073060782, 37.602623417649006, 128.73755931481043);
	var border3 = _daumMap.MapStatus.newBorder(35.08096256647576,
			127.2143901166273, 36.16848968338158, 128.9997977810616);
	var border4 = _daumMap.MapStatus.newBorder(35.79041534736719,
			127.24742885658287, 36.87690105249994, 129.0497008353627);
	var mapTestArr = [];

	
	var testMode=[];
	testMode.push({mode:0,name:'carCode 12 : date : 2013-09-03', carCode:12, date:'2013-09-03'});
	testMode.push({mode:1,name:'carCode 12 : date : 2013-09-17', carCode:12, date:'2013-09-17'});
	testMode.push({mode:2,name:'carCode 12 : date : 2013-09-13', carCode:12, date:'2013-09-13'});
	var test={};
	function setTestMode(mode){
		
		test.mode = mode;
		test.carCode = testMode[mode].carCode;
		test.date = testMode[mode].date;
		$('h1').text(mode+'  '+testMode[mode].name);
	}
	function test1(input) {
		
		var mode = test.mode+1;
		if(mode>=testMode.length) mode=0;
		setTestMode(mode);
		$(input).val('테스트모드'+mode);
	}

	var _this = this;
	_this.lines = [];

	function test2() {
		var options = {};
		options['endArrow'] = true;
		var line = new daum.maps.Polyline(options);
		var path = [];

		var url = '/map/getCarRouteTest.json';
		var yy = prompt('분 입력')||4;
		var param = {
			carCode : test.carCode,
			date : test.date,
			yy : yy
		};
		AjaxPost(url, param, function(data) {
			var lastLatLng = null;
			for ( var i = 0; i < data.list.length; i++) {
				var arr = data.list[i];
				for ( var j = 0; j < arr.length; j++) {
					if(outOfKoreaRange(arr[j].lat, arr[j].lng)) continue;
					if (lastLatLng && j == 0) {
						makeNewLine(lastLatLng, new daum.maps.LatLng(
								arr[j].lat, arr[j].lng));
					}
					lastLatLng = new daum.maps.LatLng(arr[j].lat, arr[j].lng);
					path.push(lastLatLng);
				}
				line.setPath(path);
				line.setMap(_daumMap.map);
				_this.lines.push(line);
				path = [];
				line = new daum.maps.Polyline(options);

			}

		});
	}

	function makeNewLine(latLng1, latLng2) {
		var options = {
			strokeColor : '#e10000',
			fillColor : '#0000f1',
			strokeWeight : 5,
			strokeOpacity : 0.3
		};

		var line = new daum.maps.Polyline(options);
		var path = [];
		path.push(latLng1);
		path.push(latLng2);
		line.setPath(path);
		line.setMap(_daumMap.map);
		_this.lines.push(line);
	}
	function test3() {
		while (_this.lines) {
			var line = _this.lines.pop();
			line.setMap(null);
		}
	}
	function test4() {
		
		makePagingOnMap();
		
	}
	function test5() {
		focusInPaging(prompt('테이블 index = ')||1);
	}

	var markerSetting = {
		paging : {},
		period : 2,
		zoom : 4
	};
	var _infoWindow={
			m110:[],
			m120:[]
			
	};
	function isNullNaN(str) {

		if (str == null)
			return true;
		if (isNaN(str))
			return true;
		return false;
	}
	function makePagingOnMap() {
		//logs('makePagingOnMap()');

		var url = '/map/makeMarkerOnMap.json';

		markerSetting.paging.carCode = test.carCode;
		markerSetting.paging.zoom = 5;

		markerSetting.paging.date = test.date;

		var param = markerSetting.paging;

		AjaxPost(url, param, function(data) {

			$.each(data.data, function(index, value) {
				value.detectTimeOri = value.detectTime;
				value.detectTime = formatter
						.timeFormatHHMMSS2nd(value.detectTime);
				value.startUp = startUp == 'y' ? 'On' : 'Off';
				value.speed = value.speed + 'km/h';
				value.dayDistance = formatter
						.numberComma((value.dayDistance / 10) + '')
						+ 'km';
				value.totalDistance = formatter
						.numberComma((value.totalDistance / 10) + '')
						+ 'km';

				value.cdmastate = value.cdmastate == 0 ? '이상' : '정상';
				value.gpsstate = value.gpsstate == 0 ? '이상' : '정상';
				value.voltage = isNullNaN(value.voltage) ? '-'
						: (value.voltage / 10) + 'V';
				//logs('typeof value.temperature = '+typeof value.temperature);
				//logs(value.temperature);
				value.temperature = isNullNaN(value.temperature) ? '-'
						: value.temperature + 'C';
				value.humidity = isNullNaN(value.humidity) ? '-'
						: value.humidity + '%';

			});

			try {
				if (_infoWindow.m120.length > 0) {
					while ((_infoWindow.m120.length > 0)) {
						var info = _infoWindow.m120.pop();
						info.close();
					}
					_infoWindow.m120 = [];
				}
			} catch (e) {
			}

			$('#pagingTbl').find('tr td#seq').filter(function(ind) {
				$(this).parent().find('td').css('background-color', '');
			});

			_this.pagingTbl.tableAutoSync(data.data);

			$('#searchInfo').find('#dayDistanceStr').text(
					parseInt(data.dayDistanceStr) / 10 + "Km");

			markerSetting.paging.totalPage = data.totalPage.totalPage;
			makingPaging();
		});

	}
	function makingPaging() {
		logs(makingPaging.caller&&makingPaging.caller.name||'Not in Function');
		$('#pagenation').html("");
		logs(markerSetting);
		var totalPage = markerSetting.paging.totalPage;
		var nowPage = markerSetting.paging.page||1;
		var html = '';
		var className = '';
		var setFunctionName = '';
		var index = (nowPage - 4);
		var indexCount = 0;

		if (index > 1) {
			html += '<span style="cursor:pointer;" onclick="changePaging('
					+ index
					+ ',\'before\''
					+ ')">....</span><img src="${imgUrl }/page_num_border.png"/>';

		}
		//		//logs('totalPage/20 = '+totalPage/20);
		for (; index <= (totalPage / 20 + 1); index++) {
			if ((index) == nowPage) {
				className = ' class="current_page"';
				setFunctionName = '';
			} else {
				className = 'style="cursor:pointer;"';
				setFunctionName = ' onclick="changePaging(' + index + ')"';
			}

			if (index > 0) {

				html += '<span '+className+' '+setFunctionName+'>' + index
						+ '</span><img src="${imgUrl }/page_num_border.png"/>';

				indexCount++;
			}
			if (indexCount > 9) {
				html += '<span style="cursor:pointer;" onclick="changePaging('
						+ index + ',\'after\'' + ')">' + '....' + '</span>';
				break;
			}

		}
		$('#pagenation').html(html);
		try {
			if (markerSetting.paging.makeNewPage > 0) {
				var index = markerSetting.paging.makeNewPage;
				markerSetting.paging.makeNewPage = 0;
				focusInPaging(index);
			}
		} catch (e) {
		}

	}
	

	function focusInPaging(index){
		if(index>markerSetting.paging.totalPage) return;	// totalPage 보다 가려는 곳이 크면 그냥 리턴한다.
		jsonLog(markerSetting.paging);
		var page = markerSetting.paging.page||1;
		logs('page = '+page+', index = '+index+', page*20 = '+(page*20)+', (page-1)*20 = '+((page-1)*20));
		if(((page*20) < index) || ((page-1)*20 >= index)){
// 		if(!(((page-1)*20) <= index) && (page*20 >= index)){
			markerSetting.paging.makeNewPage = index;
			changePaging(Math.ceil(index/20));
			return;

		}
		$('#carInfoPopup').show();
		//logs('focusInPaging - index = '+index);
		var ret = $('#pagingTbl').find('tr td#seq').filter(function(ind){
			if($(this).text()==index)
				return $(this);
// 			$(this).parent().find('td').removeClass('highlighter');
			$(this).parent().find('td').css('background-color', '');
		});
		logs('--------------');
		logs($(ret));
		logs('--------------');
		var tr = $(ret).parent();
		$(tr).find('td').css('background-color','#FFFFCC');
		
		var trHeight = $(tr).height();
		logs('index%21-1 = '+((index-1)%20));
		logs('trIndex-1)+trHeight = '+((index-1)%20)*trHeight);
		$('.chart_body').scrollTop(((index-1)%20)*trHeight);
	}

	function changePaging(index, option) {
		logs('markerSetting.paging.totalPage = '
				+ markerSetting.paging.totalPage);
		if (option == null) {
			logs(', index = ' + index);

			markerSetting.paging.page = index;
			markerSetting.paging.start = 0;
			markerSetting.paging.end = 0;
			makePagingOnMap();
		} else {
			if (option == 'before') {
				var next = index - 3;
				while (next <= 0) {
					next++;
				}
				logs('next = ' + next + ', index = ' + index);
				markerSetting.paging.page = next;
				markerSetting.paging.start = 0;
				markerSetting.paging.end = 0;
				makePagingOnMap();
			} else if (option == 'after') {
				var next = index + 3;
				while (next >= (markerSetting.paging.totalPage / 20) + 1) {
					next--;
				}
				logs('next = ' + next + ', index = ' + index);
				markerSetting.paging.page = next;
				markerSetting.paging.start = 0;
				markerSetting.paging.end = 0;
				makePagingOnMap();
			}
		}
	}
	var rootInfowindow=null;
	function makeMarkerFocus(tr){
		logs('makeMarkerFocus(tr)');
		logs($(tr));
// 		hideCarInfoPopup();
		var data = {};
		data.seq = $(tr).find('#seq').text();
		//logs('makeMarkerFocus seq = '+seq);
		data.lat = $(tr).find('#lat').val();
		data.lng = $(tr).find('#lng').val();
		
		data.cardinal = $(tr).find('#cardinal').val();
		data.name = $(tr).find('#name').val();
// 		data.detectTime = $(tr).find('#detectTimeOri').val();
		//logs('data.detectTime = '+data.detectTime);
		moveMapTo(data.lat, data.lng);
		var position = new daum.maps.LatLng(data.lat, data.lng);
		try{
			logs('typeof rootInfowindow = '+typeof rootInfowindow);
			if(typeof rootInfowindow =='object'){
				rootInfowindow.close();	
			}
			
		}catch(e){};
		try{
			rootInfowindow = new daum.maps.InfoWindow({
				position : position,
				content: '<span class="infoWindowSpan"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+$(tr).find('#detectTime').text()+'</span>',
				removable : true
			});
			rootInfowindow.setZIndex(2);
			rootInfowindow.open(_daumMap.map);
			
		}catch(e){logs(928);logs(e);}
		

	}
	
	function test6(){
		var lat = '37.516589', lng='126.761581';
// 		var key="7839b85722fcb33465d9fab5cb94125e81c314db";	// lbs
		var key= "c0e65576464a49c3d3af37f00f69ecf238f127c0";// local
// 		lng = 546763.551060481, lat = 290718.0831855021;
		var type ="WGS84";
// 		type="KTM";
		var url="http://apis.daum.net/local/geo/coord2addr?apikey="+key+"&longitude="+lng+"&latitude="+lat+"&format=simple&output=json&inputCoordSystem="+type;
// 		AjaxPost(url, function(data) {
// 			alert(jsonLog(data));

// 		});
		$.ajax({
			url: url,
			type: "GET",
			dataType : "jsonp",
			jsonp : "callback",
			contentType : "text/json;charset=UTF-8",
			success : function(data){
				alert(jsonLog(data));
			}
			});
	}
</script>
</head>
<body>
	<h1>CarCode 12: 2013-09-03</h1>
	<ul>
		<li><input type="button" value="테스트모드" onclick="test1(this)" /></li>
		<li><input type="button" value="라인테스트" onclick="test2()" /></li>
		<li><input type="button" value="Clear line" onclick="test3()" /></li>
		<li><input type="button" value="table" onclick="test4()" /></li>
		<li><input type="button" value="테이블 이동" onclick="test5()" /></li>
		<li><input type="button" value="주소가지고 오기" onclick="test6()" /></li>
		
	</ul>
	<div id="map" class="map" style="width: 800px; height: 600px;">
		<%@ include file="/WEB-INF/views/daumMap/testDaumMap.jsp"%>
	</div>
	<!--map end -->
	<div class="chart_body" style="height:200px;overflow:auto">
		<table id="pagingTbl" valign="top" cellpadding="0" cellspacing="0">
			<tbody>
				<tr onclick="makeMarkerFocus(this)">
					<td id="seq" width="40px">3</td>
					<td id="startUp" width="40px">ON</td>
					<td id="detectTime" width="95px">04-04 14:55:05</td>
					<td id="address" width="170px" style="white-space: normal">경기도
						부천시 원미구 중동 유럽 미국 일본 100m전</td>
					<td id="speed" width="50px">81Km</td>
					<td id="rpm" width="50px">2345</td>
					<td id="cardinalStr" width="50px">-</td>
					<td id="breaked" width="50px">ON</td>
					<td id="dayDistance" width="65px">50Km</td>
					<td id="totalDistance" width="65px">-</td>
					<td id="cdmastate" width="45px">-</td>
					<td id="gpsstate" width="40px">-</td>
					<td id="voltage" width="40px">0</td>
					<td id="temperature" width="40px">0</td>
					<td id="humidity" width="40px">습도</td>
					<td width="*">-</td>
					<td style="display: none"><input type="hidden" id="lat"
						name="lat" /> <input type="hidden" id="lng" name="lng" /> <input
						type="hidden" id="cardinal" name="cardinal" /> <input
						type="hidden" id="name" name="name" /> <input type="hidden"
						id="detectTimeOri" name="detectTimeOri" /></td>
				</tr>
			</tbody>

		</table>
	</div>
	<div id="pagenation">
				<span class="current_page">1</span><img src="${imgUrl }/page_num_border.png"/>
				<span>2</span><img src="${imgUrl }/page_num_border.png"/>
				<span>3</span><img src="${imgUrl }/page_num_border.png"/>
				<span>4</span><img src="${imgUrl }/page_num_border.png"/>
				<span>5</span><img src="${imgUrl }/page_num_border.png"/>
				<span>6</span><img src="${imgUrl }/page_num_border.png"/>
			</div>
	<!-- firstChart is the scroll table end -->
</body>
</html>
